import router, { asyncRoutes } from "./router"
import store from './store'
import NProgress from 'nprogress' // progress bar
import getPageTitle from "@/utils/get-page-title";
import { asyncRoutes8 } from "@/router/index";
//白名单：不需要token就可以直接访问页面
const whiteList = ['/login','/404']

//导航守卫
router.beforeEach(async(to, from, next) => {
  //获取token
  const token = store.state.user.token
  if (token) {
      //是否去登录
    if (to.path === '/login') {
      //跳到主页
      console.log('已跳到主页,不能访问登录login');
      next('/')
      NProgress.done()
    } else {
      //有token,正常访问页面
      //发请求拿信息：调用action
      //(.vue,this.$store.dispatch())
      //判断个人信息
      const userInfo = store.state.user.userInfo
      if (!userInfo.userId) {
        const res = await store.dispatch("user/getUserProfile");

        const menus = res.data.roles.menus;
        console.log(asyncRoutes8);
        const filterRotes = asyncRoutes8.filter((item) => {
          const name = item.children[0].name;

          return menus.includes(name);
        });
        //根据用户的权限信息，从asyncRoutes8过滤出一部分
        console.log("路由守卫", filterRotes, asyncRoutes8, res.data.roles.menus);
        //可以让我们在地址栏中访问页面
        //404在整个路由配置的最后面
        filterRotes.push({ path: "*", redirect: "/404", hidden: true });
        router.addRoutes(filterRotes);
        //把动态的路由添加到vuex
        store.commit("menu/updateMenuList", filterRotes); 
        next({
          ...to,
          replace: true,
        })
      } else {
        next()
      } 
      
    }
  } else {
    //是否去白名单：/login
    if (whiteList.includes(to.path)) {
      next()
    } else {
      //没有token,去的不是login
      next('/login')
      NProgress.done()
    }
  }
  // console.log('从', from)
  // console.log('去',to)
  // next()
})

router.beforeEach((to, from, next) => {
  document.title = getPageTitle(to.meta.title);
  next();
});

router.afterEach((to,from) => {
  console.log('页面跳转结束', to.path)
  NProgress.done()
})

// import { Message } from 'element-ui'
// import 'nprogress/nprogress.css' // progress bar style
// import { getToken } from '@/utils/auth' // get token from cookie
// import getPageTitle from '@/utils/get-page-title'

// NProgress.configure({ showSpinner: false }) // NProgress Configuration

// const whiteList = ['/login'] // no redirect whitelist

// router.beforeEach(async(to, from, next) => {
//   // start progress bar
//   NProgress.start()

//   // set page title
//   document.title = getPageTitle(to.meta.title)

//   // determine whether the user has logged in
//   const hasToken = getToken()

//   if (hasToken) {
//     if (to.path === '/login') {
//       // if is logged in, redirect to the home page
//       next({ path: '/' })
//       NProgress.done()
//     } else {
//       const hasGetUserInfo = store.getters.name
//       if (hasGetUserInfo) {
//         next()
//       } else {
//         try {
//           // get user info
//           await store.dispatch('user/getInfo')

//           next()
//         } catch (error) {
//           // remove token and go to login page to re-login
//           await store.dispatch('user/resetToken')
//           Message.error(error || 'Has Error')
//           next(`/login?redirect=${to.path}`)
//           NProgress.done()
//         }
//       }
//     }
//   } else {
//     /* has no token*/

//     if (whiteList.indexOf(to.path) !== -1) {
//       // in the free login whitelist, go directly
//       next()
//     } else {
//       // other pages that do not have permission to access are redirected to the login page.
//       next(`/login?redirect=${to.path}`)
//       NProgress.done()
//     }
//   }
// })

// router.afterEach(() => {
//   // finish progress bar
//   NProgress.done()
// })
